<template>
	<view class="total">
		<!-- 底部按钮  -->
		<view class="bottomBtn">
			<!-- 分享按钮  -->
			<view class="flex-left">
				<button plain="true" open-type="share">
					<image src="/static/images/share.svg" mode="aspectFit"></image>
					<text>分享</text>
				</button>
			</view>
			<!-- 购物车按钮 -->
			<view class="flex-left shopping-amount" @click="goCart">
				<image src="/static/images/shopping.svg" mode="aspectFit"></image>
				<text>购物车</text>
				<text class="amount" v-if="Order.shop_cart_num>0">{{Order.shop_cart_num}}</text>
			</view>
			
			<!-- 收藏按钮 -->
			<view class="flex-left" @click="toCollect(collectNum)">
				<image src="/static/images/collect.svg" mode="aspectFit" v-if="collectNum <= 0"></image>
				<image src="/static/images/have-collected.svg" mode="aspectFit" v-else></image>
				<text>{{collectNum > 0 ? '已收藏' : '收藏'}}</text>
			</view>

			<view v-if="isShow" class="flex-right shopping-cart" @click="operation('add-cart',skuData)">加入购物车</view>

			<view v-if="isShow" class="flex-right buy" @click="operation('buy-now',skuData)">立即购买</view>

			<!-- 库存不足 商品已下架 -->
			<view v-else class="flex-right tip">
				<view>
					{{tips}}
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { defineProps, watch, reactive, toRefs, ref } from 'vue'
	import { login_box, comment_box } from '@/public/package-js/passValue.js'
	import { FeedBack } from "@/public/package-js/feedBack.js"
	import {sku_popup,Order} from '@/public/package-js/passValue.js'
	
	let props = defineProps({
		goods_id: String,  //商品 id
		collectionNum: Number, // 收藏次数
		skuData: Array,  // 规格数据
		goods: Object  // 商品信息
	})

	const data = reactive({
		collectNum: 0, // 收藏次数 0--未收藏  大于 0 -- 已收藏
		goods_id: '', // 商品id
		goods: {}, // 存储传递的商品数据
		isShow: true, //是否显示立即购买和加入购物车按钮
		tips: '', // 显示'商品已下架'提示文字
	})

	const { isShow, tips, collectNum } = toRefs(data)

	// 1、根据父组件传递的的参数进行赋值以及页面的改变
	watch(props, (newVal, oldVal) => {
		let { goods_id, goods } = JSON.parse(JSON.stringify(newVal))
		data.goods_id = goods_id
		data.goods = goods;
		// 判断商品是否已下架，有无库存
		if (goods.shelves == false) { //未上架
			data.isShow = false
			data.tips = '该商品已下架'
		} else if (goods.stock <= 0) { 
			data.isShow = false
			data.tips = '该商品已售罄'
		}
	})
	
	// 2、接收父组件传来的收藏数据
	watch(() => props.collectionNum, (newVal, oldVal) => {
		data.collectNum = newVal
	})
	
	// 2-1、收藏和取消收藏
	const db = wx.cloud.database()
	async function toCollect(collectNum) {
		const user = uni.getStorageSync('user_info') //取出本地缓存的用户信息
		if (!user) {
			login_box.show = true;
			return false
		}
		if (collectNum === 0) { //没有收藏该商品
			try {
				// 增加到收藏
				await db.collection('collect_goods').add({ 
					data: { 
						goods_id: data.goods_id
					} 
				})
				data.collectNum++

				new FeedBack("收藏成功", "none").toast()

			} catch (e) {
				new FeedBack("收藏失败", "error").toast()
			}
		} else { //取消收藏
			try {
				await db.collection('collect_goods').where({ 
					goods_id: data.goods_id,
					_openid:user.openid
				}).remove()
				data.collectNum = 0
				new FeedBack("取消收藏成功", "none").toast()
			} catch (e) {
				new FeedBack("取消收藏失败", "error").toast()
			}
		}
	}


	// 3、点击加入购物车或立即购买
	async function operation(option, sku) {
		//取出本地缓存的用户信息 先判断是否
		const user = uni.getStorageSync('user_info') 
		if (!user) { 
			login_box.show = true; 
			return false 
		}
		// 判断商品是否有规格，有规格就要弹出规格弹窗，没有规格直接下一步
		if (sku.length > 0) { //有规格
			// 弹出规格窗，进行操作
			sku_popup.show = true
			sku_popup.option = option
			
		} else { //没有规格，直接加入购物车
			Order.order.buy_amount = 1
			// 加入购物车
			if (option == 'add-cart') {
				const db = wx.cloud.database()
				
				// // 加入购物车计算商品总价格
				// let subtotal = parseFloat(Order.order.goods_price * Order.order.buy_amount)
				// Order.order.subtotal = subtotal
				
				// 判断数据库是否出现相同的数据
				let res = await db.collection('shopping_cart').where({
					goods_id:Order.order.goods_id
				}).get()
				
				if(res.data.length > 0){
					// 有相同商品，向对应规格增加购买数量
					const _ = db.command
					await db.collection('shopping_cart').doc(res.data[0]._id).update({
						data: {
							buy_amount: _.inc(1)
						}
					})
					// 关闭规格弹窗
					sku_popup.show = false
				}else{			
					// 没有相同规格，向购物车添加新的数据
					await db.collection('shopping_cart').add({
						data:{
							goods_id:Order.order.goods_id,
							goods_image:Order.order.goods_image,
							goods_title:Order.order.goods_title,
							goods_price:Order.order.goods_price,
							buy_amount:Order.order.buy_amount,
							specs:Order.order.specs,
							equal_sku:Order.order.equal_sku,
							add_time:new Date().getTime()
						}
					})
					Order.shop_cart_num += 1
					sku_popup.show = false
				}
				new FeedBack("加入购物车成功","success").toast()
				// console.log("Order.order",Order.order);
				
				
			} else {
				/* 立即购买 */
				sku_popup.show = false
				// 计算总价进行赋值
				Order.order.subtotal = parseFloat(Order.order.goods_price * Order.order.buy_amount)
				sku_popup.show = false
				//  将订单信息转为数组 传递到确认订单界面
				const order = JSON.stringify([Order.order])
				uni.navigateTo({  //type=direct 表示单个商品直接购买下单
					url: `/pages/confirm-order/confirm-order?order=${order}&type=direct`
				})
			}
		}
	}

	// 4、跳转购物车
	function goCart() {
		uni.switchTab({
			url: '/pages/shopping-cart/shopping-cart'
		})
	}
</script>

<style scoped>
	.total {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #fefefe;
		border-top: 1rpx solid #e3e3e4;
		height: 110rpx;
	}

	.bottomBtn {
		padding: 0 10rpx 0 10rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.bottomBtn image {
		width: 40rpx;
		height: 40rpx;
		display: block;
		padding-bottom: 8rpx;
	}

	.flex-left {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		font-size: 25rpx;
		color: #8a8b90;
		margin-top: 20rpx;
	}

	.flex-left button {
		border: navajowhite;
		padding: inherit !important;
		margin: 0 !important;
		font-size: 25rpx !important;
		line-height: inherit !important;
		color: #8a8b90 !important;
	}

	.flex-right {
		flex: 2;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		margin-top: 15rpx;
	}

	.shopping-cart {
		background-color: #fdf5f7;
		color: #ec697f;
		font-weight: bold;
		border-radius: 50rpx 0 0 50rpx;
	}

	.buy {
		background-color: #e9445a;
		color: #fefefe;
		font-weight: bold;
		border-radius: 0 50rpx 50rpx 0;
	}
	.tip{
		padding: 0 35rpx 0 10rpx;
		flex: 3;
	}
	
	.tip view{
		background-color: #e9445a;
		color: #fefefe;
		font-weight: bold;
		border-radius: 50rpx;
	}

	.shopping-amount {
		position: relative;
		/* width:32rpx !important; */
		/* border: 1px solid red; */
	}


	.amount {
		position: absolute;
		right: 0rpx;
		top: -4rpx;
		background-color: #e9445a;
		color: #FFFFFF;
		width: 40rpx;
		height: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20rpx;
		border-radius: 50rpx;
	}
</style>
